package com.asm.service;

import com.asm.dto.PageResult;
import com.asm.entity.sys.Tag;
import com.asm.repository.TagRepository;
import com.asm.util.SnowflakeIdWorker;
import com.asm.vo.sys.TagVo;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author morningbear
 */
@Service
public class TagService {

    @Resource
    private TagRepository tagRepository;

    @Resource
    private SnowflakeIdWorker snowflakeIdWorker;

    /**
     * 获取小区分页结果
     *
     * @param pageSize   页面大小
     * @param pageNumber 当前页码
     * @param page       分页
     * @return 分页结果
     */
    private PageResult<TagVo> getCommunityVoPageResult(Integer pageSize, Integer pageNumber, Page<Tag> page) {
        List<TagVo> communityList = new ArrayList<>();
        for (Tag tag : page.getContent()) {
            TagVo tagVo = new TagVo();
            BeanUtils.copyProperties(tag, tagVo);
            communityList.add(tagVo);
        }
        return new PageResult<>(pageNumber, pageSize, page.getTotalPages(), communityList);
    }

    /**
     * 查询所有标签
     */
    public PageResult<TagVo> findAllTags(Integer pageNumber, Integer pageSize) {
        Page<Tag> tagPage = tagRepository.findAll(PageRequest.of(pageNumber, pageSize));
        return getCommunityVoPageResult(pageSize, pageNumber, tagPage);
    }

    /**
     * 添加标签
     */
    @Transactional(rollbackFor = Exception.class)
    public Long addTag(TagVo tagVo) {
        Tag tag = new Tag();
        BeanUtils.copyProperties(tagVo, tag);
        tag.setId(snowflakeIdWorker.nextId());
        tag.setCreateAt(new Date());
        tag.setCreateBy(1L);
        tag.setUpdateAt(new Date());
        tag.setUpdateBy(1L);
        tagRepository.save(tag);
        return tag.getId();
    }

    /**
     * 删除标签
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteTag(Long id) {
        Tag tag = tagRepository.findById(id).get();
        tag.setIsDel(true);
        tag.setUpdateBy(1L);
        tag.setUpdateAt(new Date());
        tagRepository.save(tag);
    }

    /**
     * 更新标签
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateTag(TagVo tagVo) {
        Tag tag = tagRepository.findById(tagVo.getId()).get();
        BeanUtils.copyProperties(tagVo, tag);
        tag.setUpdateBy(1L);
        tag.setUpdateAt(new Date());
        tagRepository.save(tag);
    }

}
